package car;

import com.opencsv.CSVReader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class xiaoliang2 {

    public static class MyMapper extends Mapper<Object, Text, Text, IntWritable> {
        private Text month = new Text();

        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            try {
                // 使用 GBK 编码解析输入行
                ByteArrayInputStream inputStream = new ByteArrayInputStream(value.getBytes());
                InputStreamReader reader = new InputStreamReader(inputStream, "GBK");
                CSVReader csvReader = new CSVReader(reader);

                String[] row;
                while ((row = csvReader.readNext()) != null) {
                    if (row.length >= 12) { // 确保列数足够（索引从0开始）
                        String monthStr = row[1].trim();   // B列：月份
                        String salesStr = row[11].trim();  // L列：销量

                        try {
                            int sales = Integer.parseInt(salesStr);
                            month.set(monthStr);
                            context.write(month, new IntWritable(sales));
                        } catch (NumberFormatException e) {
                            System.err.println("无效销售数字: " + salesStr + " 行: " + String.join(",", row));
                        }
                    } else {
                        System.err.println("字段不足，需要12列，当前: " + row.length + " 行: " + String.join(",", row));
                    }
                }

                csvReader.close();
            } catch (Exception e) {
                System.err.println("处理行失败: " + value.toString());
                e.printStackTrace();
            }
        }
    }

    public static class MyReducer extends Reducer<Text, IntWritable, Text, DoubleWritable> {
        private Map<Text, Long> map = new HashMap<>();
        private long total = 0;

        @Override
        public void reduce(Text key, Iterable<IntWritable> values, Context context)
                throws IOException, InterruptedException {
            long sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            total += sum;
            map.put(new Text(key), sum);
        }

        @Override
        public void cleanup(Context context) throws IOException, InterruptedException {
            if (total == 0) {
                System.err.println("总销售额为0，无法计算占比");
                return;
            }

            Set<Text> ks = map.keySet();
            for (Text t : ks) {
                long sales = map.get(t);
                double ratio = (double) sales / total;
                context.write(new Text(t.toString() + " month_sales"), new DoubleWritable(ratio));
            }
        }
    }

    public static void main(String[] args) throws Exception {
        String namenode_ip = "192.168.128.130";
        String hdfs = "hdfs://" + namenode_ip + ":8020";
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", hdfs);

        String jobName = "monthly_analysis";
        Job job = Job.getInstance(conf, jobName);
        job.setMapperClass(MyMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setReducerClass(MyReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(DoubleWritable.class);

        String dataDir = "/car/data.csv";
        String outputDir = "/Outputche/v3";
        Path inPath = new Path(hdfs + dataDir);
        Path outPath = new Path(hdfs + outputDir);

        FileSystem fs = FileSystem.get(conf);

        // 输入路径检查
        if (!fs.exists(inPath)) {
            System.err.println("输入路径不存在: " + inPath);
            System.exit(1);
        }

        // 安全删除输出路径
        if (fs.exists(outPath)) {
            if (!fs.delete(outPath, true)) {
                System.err.println("无法删除输出路径: " + outPath);
                System.exit(1);
            }
        }

        FileInputFormat.addInputPath(job, inPath);
        FileOutputFormat.setOutputPath(job, outPath);

        System.out.println("Job: " + jobName + " is running...");
        if (job.waitForCompletion(true)) {
            System.out.println("success!");
        } else {
            System.out.println("failed!");
            System.exit(1);
        }
    }
}
